package com.ruoyi.cangku.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.cangku.domain.Shangpinguanli;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Component
public class tiaoMaAuto {


    private static String env;

    @Value("${ruoyi.profile}")
    public void setEnv(String env) {
        tiaoMaAuto.env = env;
    }

    // 二维码尺寸
    private static final int QRCODE_SIZE = 350;

    public static String QRCote(Shangpinguanli shangpinxinxi, String url) throws IOException {
        //private static final String filePath = "C:/ruoyi/uploadPath/upload/ChuKuDan/";
        //private static final String filePath = "D:/";
        String filePath = env + "/upload/TiaoMa/";
//        String filePath = "D:/";
        String md54name = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 将要加密的文本转换为字节数组，然后更新Digest对象
            md.update(shangpinxinxi.getShangpinbianhao().getBytes());

            // 计算最终的摘要结果，返回值为一个字节数组
            byte[] digest = md.digest();

            // 将字节数组转换为16进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            md54name = sb.toString();
            File file = new File(filePath + md54name + ".jpg");
            ImageIO.write(createTheQRCode(shangpinxinxi), "jpg", file);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return url + "/profile/upload/TiaoMa/" + md54name + ".jpg";
    }

    private static BufferedImage createTheQRCode (Shangpinguanli shangpinxinxi) throws NoSuchAlgorithmException {
        // 二维码基本参数设置
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 设置编码字符集utf-8
        //hints.put(EncodeHintType.CHARACTER_SET, CharacterSetECI.UTF8);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //hints.put(EncodeHintType.CHARACTER_SET, "GBK");
        // 设置纠错等级L/M/Q/H,当二维码被损毁一部分时，纠错等级越高，越可能读取成功；同样的，纠错等级越高，单位面积内点阵的点越多，机器扫描时，识别所需时间越长，当前设置等级为最高等级H
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 可设置范围为0-10，但仅四个变化0 1(2) 3(4 5 6) 7(8 9 10)
        hints.put(EncodeHintType.MARGIN, 0);

        // 生成图片类型为QRCode
        BarcodeFormat format = BarcodeFormat.QR_CODE;
        // 创建位矩阵对象
        BitMatrix matrix = null;

        try {
            // 生成二维码对应的位矩阵对象
            matrix = new MultiFormatWriter().encode(shangpinxinxi.getShangpinbianhao(), format, QRCODE_SIZE, QRCODE_SIZE, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        // 设置位矩阵转图片的参数
        MatrixToImageConfig config = new MatrixToImageConfig(Color.black.getRGB(), Color.white.getRGB());
        // 位矩阵对象转BufferedImage对象
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(matrix, config);

        return NoteAdd(bufferedImage, shangpinxinxi);
    }

    private static BufferedImage NoteAdd(BufferedImage image, Shangpinguanli shangpinguanli) {
        //缩放二维码
        Image src = image.getScaledInstance(QRCODE_SIZE, QRCODE_SIZE, Image.SCALE_DEFAULT);
        //生成新图片用于写图注
        BufferedImage textImg = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        //设置图注字体
        Font font = new Font("微软雅黑", Font.BOLD, 24);
        //设置画笔
        Graphics2D g2d = textImg.createGraphics();
        g2d.setFont(font);

        //要写入的图注
        String leibieText = "商品类别：" + shangpinguanli.getShangpinleibie();
        String mingchengText1 = "商品名称：";
        String mingchengText2 = shangpinguanli.getShangpinming();
        String guigeText = "规格：" + shangpinguanli.getShangpinguigekuan() + "X" + shangpinguanli.getShangpinguigegao();
        String kaixiangText = "开向：" + shangpinguanli.getShangpinkaixiang();

        //获取各行字的尺寸
        int[] leibieSize = sizeCheckAndReturn(g2d,leibieText);
        int[] mingchengSize1 = sizeCheckAndReturn(g2d,mingchengText1);
        int[] mingchengSize2 = sizeCheckAndReturn(g2d,mingchengText2);
        int[] guigeSize = sizeCheckAndReturn(g2d,guigeText);
        int[] kaixiangSize = sizeCheckAndReturn(g2d,kaixiangText);

        //确定新图片的大小
        int widthNew = QRCODE_SIZE;
        if (mingchengSize2[1] >= QRCODE_SIZE) {
            widthNew = mingchengSize2[1];
        }
        int heightNew = QRCODE_SIZE+leibieSize[2]+mingchengSize1[2]+mingchengSize2[2]+guigeSize[2]+kaixiangSize[2]+10;
        textImg.flush();
        //生成新图片
        BufferedImage text2Image = new BufferedImage(widthNew,heightNew,BufferedImage.TYPE_INT_RGB);
        g2d = text2Image.createGraphics();
        g2d.setFont(font);
        //因为BufferedImage.TYPE_INT_RGB默认是黑底白字，所以要重写背景色和字体颜色设置
        g2d.setPaint(Color.WHITE);
        g2d.fillRect ( 0, 0, text2Image.getWidth(), text2Image.getHeight() );
        g2d.setColor(Color.BLACK);
        //绘制二维码
        if (mingchengSize2[1] >= QRCODE_SIZE) {
            g2d.drawImage(src, (mingchengSize2[1]-QRCODE_SIZE) / 2, 0,null);
        }else {
            g2d.drawImage(src, 0,0,null);
        }
        //绘制图注
        int jianju = 2+leibieSize[3];
        g2d.drawString(leibieText,(widthNew-leibieSize[1])/2,QRCODE_SIZE+jianju);
        jianju += leibieSize[2];
        g2d.drawString(mingchengText1,(widthNew-mingchengSize1[1])/2,QRCODE_SIZE+jianju);
        jianju += mingchengSize1[2];
        g2d.drawString(mingchengText2,(widthNew-mingchengSize2[1])/2,QRCODE_SIZE+jianju);
        jianju += mingchengSize2[2];
        g2d.drawString(guigeText,(widthNew-guigeSize[1])/2,QRCODE_SIZE+jianju);
        jianju += guigeSize[2];
        g2d.drawString(kaixiangText,(widthNew-kaixiangSize[1])/2,QRCODE_SIZE+jianju);
        //关闭绘制
        text2Image.flush();
        g2d.dispose();

        return text2Image;
    }

    public static int[] sizeCheckAndReturn(Graphics2D graphics2D, String text){
        // INFO: Dechert: 2021/1/7 获取画笔的字体
        Font font = graphics2D.getFont();
        // INFO: Dechert: 2021/1/7 通过JLabel获取文本的总长度和总高度
        JLabel jLabel = new JLabel(text);
        jLabel.setFont(font);
        FontMetrics fontMetrics = jLabel.getFontMetrics(font);
        int textLength = text.length();
        int totalWidth = fontMetrics.stringWidth(text); //一行的总长度，用于判断是否超出了范围
        int textHeight = fontMetrics.getHeight(); //计算一行的高度
        int textAscent = fontMetrics.getAscent(); //计算基准线以居中文字
        return new int[]{textLength,totalWidth,textHeight,textAscent};
    }

    public static void main(String[] args) throws IOException {
//        Shangpinguanli shangpinguanli = new Shangpinguanli();
//        shangpinguanli.setShangpinbianhao("123456");
//        shangpinguanli.setShangpinming("7公分铝合金钢制防火门aaabbbccceeefff880*2080");
//        shangpinguanli.setShangpinguigekuan(1180);
//        shangpinguanli.setShangpinguigegao(2080);
//        shangpinguanli.setShangpinkaixiang("外左开");
//        shangpinguanli.setShangpinleibie("防火门（左扇）");
//        BufferedImage bfi = NoteAdd(null,shangpinguanli);
//        ImageIO.write(bfi, "JPEG", Files.newOutputStream(Paths.get("D:/test.jpg")));
//        File file = new File("D:/test.jpg");
//        ImageIO.write(bfi, "jpg",file);
//        System.out.println(QRCote(shangpinguanli,"https://123.123.123.123"));
//        String url = "https://www.beilianjd.com:10270/profile/upload/TiaoMa/a9268439cc48f21ea5d53d66dad1811f.jpg";
//        String[] urlList = url.split("/");
//        String urlNew = urlList[urlList.length-1].replace(".jpg","");
//        System.out.println(urlNew);
    }
}
